// 手机号校验
export const valiteMobile = val => {
	const regex = /^1[3-9]\d{9}$/;
	return regex.test(val);
}

// 证件号校验
export const valiteCard = val => {
	if (!/^\d{15}$|^\d{17}[\dXx]$/.test(val)) return false;

	// 18 位身份证校验规则
	if (val.length === 18) {
		const factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]; // 权重因子
		const checkCode = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']; // 校验码

		let sum = 0;
		for (let i = 0; i < 17; i++) {
			sum += val[i] * factor[i];
		}
		const lastChar = checkCode[sum % 11];

		return lastChar === val[17].toUpperCase();
	}

	return true;
}

export const objToQueryString = (obj) => {
	return Object.keys(obj)
		.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`)
		.join("&");
}

// 名字划*号
export const maskName = name => {
	if (name.length <= 2) return name[0] + '*'; // 如果名字太短，不处理
	return name[0] + '*'.repeat(name.length - 2) + name[name.length - 1];
}

// 身份证
export const maskIDCard = (idCard) => {
	if (idCard.length === 15) {
		return idCard.replace(/^(\d{6})\d{6}(\d{3})$/, '$1******$2');
	} else if (idCard.length === 18) {
		return idCard.replace(/^(\d{6})\d{8}(\d{4})$/, '$1********$2');
	}
	return idCard;
}

// 手机号
export const maskMobile = (phone) => {
	if (phone.length === 11) {
		return phone.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2');
	} else if (phone.length === 7) { // 处理 7 位短号
		return phone.replace(/^(\d{3})\d{2}(\d{2})$/, '$1**$2');
	}
	return phone;
}

// 千分位
export const formatNumber = data => {
	return Number(num || 0).toLocaleString()
}